/*
 * Created on Feb 5, 2009
 *
 * TODO
 */
package jacky.lanlan.song.extension.vraptor2;

import org.vraptor.LogicDefinition;
import org.vraptor.LogicException;
import org.vraptor.LogicFlow;
import org.vraptor.component.LogicMethod;
import org.vraptor.http.VRaptorServletResponse;
import org.vraptor.view.ViewException;

/**
 * 实现 {@code RawOut} 的功能。需要依赖 {@code ComponentLookupInterceptor} 和 {@code
 * SettingAndValidationInterceptor}
 * <p>
 * <i>不需要直接用这个拦截器，请使用 {@code EnhanceInterceptor}</i>
 * 
 * @author Jacky.Song
 */
public class RawResponseInterceptor extends BaseInterceptor {

	@Override
	protected boolean canIntercept(LogicMethod logic) {
		// 过滤 @RawOut 标注的方法
		return logic.getMetadata().isAnnotationPresent(RawOut.class) && logic.getMetadata().getReturnType() == String.class;
	}

	@Override
	protected void doIntercept(LogicFlow flow) throws LogicException, ViewException {
		try {
			LogicMethod logic = getLogicMethod(flow);
			RawOut raw = logic.getMetadata().getAnnotation(RawOut.class);

			// 手动调用Logic方法，目的是得到返回值
			LogicDefinition define = getLogicDefinition(flow);
			String result = logic.execute(define.getComponent(), flow.getLogicRequest(), define.getParameters());
			/*
			 * 这里，需要 ComponentLookupInterceptor 提供 Component 实例，否则define.getComponent()返回null 需要
			 * SettingAndValidationInterceptor 提供 方法参数，否则define.getParameters()返回空数组[]
			 */
			// 直接输出结果到响应，实现 @RawOut 语义
			VRaptorServletResponse resp = getResponse(flow);
			resp.setContentType(raw.contentType());
			writeAndClose(result.getBytes(raw.encoding()), resp.getOutputStream());
		}
		catch (Exception e) {
			throw new LogicException("@RawOut 输出响应时出错： " + e);
		}
	}

}
